/*
 * Logic implementation of the Snake game. It is designed to efficiently
 * represent the state of the game in memory.
 *
 * This code is public domain. Feel free to use it for any purpose!
 */

#define SDL_MAIN_USE_CALLBACKS 1 /* use the callbacks instead of main() */
#include <SDL3/SDL.h>
#include <SDL3/SDL_main.h>
#include "common/point.h"
#include "snake/snake_app.h" 
   
SnakeApp app;
 
SDL_AppResult SDL_AppIterate(void *appstate)
{
    return app.iterate();
}

static const struct
{
    const char *key;
    const char *value;
} extended_metadata[] =
{
    { SDL_PROP_APP_METADATA_URL_STRING, "https://examples.libsdl.org/SDL3/demo/01-snake/" },
    { SDL_PROP_APP_METADATA_CREATOR_STRING, "SDL team" },
    { SDL_PROP_APP_METADATA_COPYRIGHT_STRING, "Placed in the public domain" },
    { SDL_PROP_APP_METADATA_TYPE_STRING, "game" }
};
 
SDL_AppResult SDL_AppInit(void **appstate, int argc, char *argv[])
{
    if (!SDL_SetAppMetadata("Example Snake game", "1.0", "com.example.Snake")) {
        return SDL_APP_FAILURE;
    }

    for (size_t i = 0; i < SDL_arraysize(extended_metadata); i++) {
        if (!SDL_SetAppMetadataProperty(extended_metadata[i].key, extended_metadata[i].value)) {
            return SDL_APP_FAILURE;
        }
    }

    if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK)) {
        SDL_Log("Couldn't initialize SDL: %s", SDL_GetError());
        return SDL_APP_FAILURE;
    }

    return app.openWindow();
}
 
SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event)
{
    switch (event->type) {
    case SDL_EVENT_QUIT:
        return SDL_APP_SUCCESS;
    case SDL_EVENT_JOYSTICK_ADDED:
        app.openJoyStick(event->jdevice.which);
        break;
    case SDL_EVENT_JOYSTICK_REMOVED:
        app.closeJoyStick(event->jdevice.which);
        break;
    case SDL_EVENT_JOYSTICK_HAT_MOTION:
        return app.handle_hat_event(event->jhat.value);
    case SDL_EVENT_KEY_DOWN:
        return app.handle_key_event(event->key.scancode);
    default:
        break;
    }
    return SDL_APP_CONTINUE;
}
 
void SDL_AppQuit(void *appstate, SDL_AppResult result)
{
    app.closeWindow();
}